import { IUserMenu, } from "@/types/userType"
import { RouteRecordRaw} from "vue-router"

const urls:any[] = []
// 递归函数
function matchUrl(menu:any) {
  if (menu.type !== 1) {
    if(menu instanceof Array) {
      menu.forEach(m => {
        urls.push(m.url)
      })
    }else {
      urls.push(menu.url)
    }
  }else {
    matchUrl(menu.children)
  }
}
export default function loadRoutes (userMenus:IUserMenu[]): RouteRecordRaw[] {

  const routes:RouteRecordRaw[] =[]
  // 1. 加载所有路由组件
  const allRoutes:RouteRecordRaw[] = []
  // 取到所有文件对象
  const routeFiles = require.context("./main/system", true, /\.ts/)

  // 返回匹配到的所有文件的 相对路径
  routeFiles.keys().forEach(key => {

    // 获取路由对象
    const route:RouteRecordRaw = require("./main/system" + key.slice(1)).default
    allRoutes.push(route)
  })

  userMenus.forEach(menu => {

    matchUrl(menu)
  })

  allRoutes.forEach(item =>{
    urls.forEach(url => {
      if(url == item.path){
        routes.push(item)
      }
    })
  })
  // 全局

  return routes
}
